package com.activity.content;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSONObject;
import com.example.login.R;
import com.tools.Address;
import com.tools.CommonDialog;
import com.tools.CommonThings;
import com.tools.NodeView;
import com.tools.OkHttp3;
import com.tools.PayDialog;
import com.tools.goods.Goods;

import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.RequestBody;
import okhttp3.Response;

public class GoodsDetail extends AppCompatActivity {
    private ImageView back, refresh;
    private TextView name, risk, rate, minAmount, increaseAmount, term;
    private Button deposit;
    private Goods goods;
    private JSONObject detailJSON;
    private LinearLayout scrollLinear;
    private NodeView nodeView;
    private List<String> titleList = new ArrayList<>();
    private List<String> nodeList = new ArrayList<>();
    private String money;

    Handler handler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(Message msg) {
            switch (msg.what){
                case 0x001:
                    JSONObject dataJSON = detailJSON.getJSONObject("data");

                    break;
            }
            return false;
        }
    });

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_goods_detail);
        initView();
        goods = getIntent().getParcelableExtra("goods");
        setData(goods);

        titleList.add("");
        titleList.add(tranTime(goods.getValueDate()));
        titleList.add(tranTime(goods.getDueDate()));
        titleList.add("");

        nodeList.add("开始销售");
        nodeList.add("起息日");
        nodeList.add("结息日");
        nodeList.add("停止销售");

        nodeView.setTitleList(titleList);
        nodeView.setNodeList(nodeList);
        try {
            nodeView.setSelectIndex(getSelectIndex());
        } catch (ParseException e) {
            e.printStackTrace();
        }

        back.setOnClickListener(view ->{
            finish();
        });

        refresh.setOnClickListener(view ->{
            Toast.makeText(GoodsDetail.this, "刷新成功", Toast.LENGTH_SHORT).show();
        });

        deposit.setOnClickListener(view ->{
            initDialog();
        });
    }

    private void initView(){
        scrollLinear = findViewById(R.id.goods_detail_scroll_linear);
        back = findViewById(R.id.goods_detail_back);
        refresh = findViewById(R.id.goods_detail_refresh);
        name = findViewById(R.id.goods_detail_name);
        risk = findViewById(R.id.goods_detail_risk);
        rate = findViewById(R.id.goods_detail_rate);
        minAmount = findViewById(R.id.goods_detail_min_amount);
        increaseAmount = findViewById(R.id.goods_detail_increase_amount);
        term = findViewById(R.id.goods_detail_term);
        deposit = findViewById(R.id.goods_detail_deposit);
        nodeView = findViewById(R.id.goods_detail_node_view);

        View view = View.inflate(GoodsDetail.this, R.layout.detail_tips, null);
        scrollLinear.addView(view);
    }

    private void setData(Goods goods){
        name.setText(goods.getName());

        risk.setText(CommonThings.getRiskGrade(goods.getRiskGrade()));
        if (goods.getRiskGrade() == 1){
            risk.setBackgroundResource(R.color.sign_warn);
        }else if (goods.getRiskGrade() == 2){
            risk.setBackgroundResource(R.color.warn);
        }

        rate.setText(CommonThings.invertPercent(goods.getAnnualInterestRate()));
        minAmount.setText(String.format(GoodsDetail.this.getResources().getString(R.string.minAmount), goods.getMinAmount()));
        increaseAmount.setText(String.format(GoodsDetail.this.getResources().getString(R.string.increaseAmount), goods.getIncreasingAmount()));
        term.setText(String.format(GoodsDetail.this.getResources().getString(R.string.productDeadline), goods.getProductDeadline()));
    }

    private void initDialog(){
        PayDialog payDialog = new PayDialog(GoodsDetail.this);
        payDialog.setInputVis(false);
        payDialog.setGoodsVis(true);
        payDialog.setOnPayClickListener(new PayDialog.OnPayClickListener() {
            @Override
            public void onPayClick() {
                if (isAmountTrue(payDialog.getGoodsMoney())){
                    money = payDialog.getGoodsMoney();
                    payDialog.dismiss();
                    initPayDialog();
                }
                else Toast.makeText(GoodsDetail.this, "请存入合适金额", Toast.LENGTH_SHORT).show();
            }
        });

        payDialog.setOnCancelClickListener(new PayDialog.OnCancelClickListener() {
            @Override
            public void onCancelClick() {
                payDialog.dismiss();
            }
        });
        payDialog.show();
    }

    private void initPayDialog(){
        PayDialog payDialog = new PayDialog(GoodsDetail.this);
        payDialog.setInputVis(true);
        payDialog.setGoodsVis(false);
        payDialog.setSecMoney(money);
        payDialog.setOnPayClickListener(new PayDialog.OnPayClickListener() {
            @Override
            public void onPayClick() {
                if (payDialog.getInputText().length() < 6)
                    Toast.makeText(GoodsDetail.this, "请输入正确密码", Toast.LENGTH_SHORT).show();
                else {
                    payDialog.dismiss();
                    Toast.makeText(GoodsDetail.this, "购买成功", Toast.LENGTH_SHORT).show();
                }
            }
        });

        payDialog.setOnCancelClickListener(new PayDialog.OnCancelClickListener() {
            @Override
            public void onCancelClick() {
                payDialog.dismiss();
            }
        });
        payDialog.show();
    }

    private boolean isAmountTrue(String amount){
        int num = Integer.parseInt(amount);
        if (amount.equals("")) return false; //为空
        if (num > goods.getLimitForOne()) return false; //超出限制
        return (num - goods.getMinAmount()) % goods.getIncreasingAmount() == 0;
    }

    private String tranTime(String time){
        return time.substring(0,10).replace("-", "/");
    }

    private int getSelectIndex() throws ParseException {
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
        Date date = new Date(System.currentTimeMillis());
        Date valueDate = formatter.parse(goods.getValueDate());
        Date dueDate = formatter.parse(goods.getDueDate());
        if (date.before(valueDate)){
            return 0;
        }else if (date.equals(valueDate) || (date.after(valueDate) && date.before(dueDate))){
            return 1;
        }else if (date.equals(dueDate)){
            return 2;
        }else if(date.after(dueDate)){
            return 3;
        }
        return 0;
    }
}